home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / DJLSR106.ARJ / SGETLINE.CC < prev    next >
C/C++ Source or Header  |  1992-03-29  |  2KB  |  66 lines

  1. //    This is part of the iostream library, providing input/output for C++.
  2. //    Copyright (C) 1991 Per Bothner.
  3. //
  4. //    This library is free software; you can redistribute it and/or
  5. //    modify it under the terms of the GNU Library General Public
  6. //    License as published by the Free Software Foundation; either
  7. //    version 2 of the License, or (at your option) any later version.
  8. //
  9. //    This library is distributed in the hope that it will be useful,
  10. //    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. //    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  12. //    Library General Public License for more details.
  13. //
  14. //    You should have received a copy of the GNU Library General Public
  15. //    License along with this library; if not, write to the Free
  16. //    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18. #include "ioprivate.h"
  19.  
  20. // Algorithm based on that used by Berkeley pre-4.4 fgets implementation.
  21.  
  22. // Read chars into buf (of size n), until delim is seen.
  23. // Return number of chars read (at most n-1).
  24. // If extract_delim < 0, leave delimited unread.
  25. // If extract_delim > 0, insert delim in output.
  26.  
  27. long streambuf::sgetline(char* buf, size_t n, char delim, int extract_delim)
  28. {
  29.     register char *ptr = buf;
  30.     if (n <= 0)
  31.     return EOF;
  32.     n--; // Leave space for final '\0'.
  33.     do {
  34.     int len = egptr() - gptr();
  35.     if (len <= 0)
  36.         if (underflow() == EOF)
  37.         break;
  38.         else
  39.         len = egptr() - gptr();
  40.     if (len >= (int)n)
  41.         len = n;
  42.     char *t = (char*)memchr((void*)_gptr, delim, len);
  43.     if (t != NULL) {
  44.         size_t old_len = ptr-buf;
  45.         len = t - _gptr;
  46.         if (extract_delim >= 0) {
  47.         t++;
  48.         old_len++;
  49.         if (extract_delim > 0)
  50.             len++;
  51.         }
  52.         memcpy((void*)ptr, (void*)_gptr, len);
  53.         ptr += len;
  54.         ptr[0] = 0;
  55.         _gptr = t;
  56.         return old_len + len;
  57.     }
  58.     memcpy((void*)ptr, (void*)_gptr, len);
  59.     _gptr += len;
  60.     ptr += len;
  61.     n -= len;
  62.     } while (n != 0);
  63.     *ptr = 0;
  64.     return ptr - buf;
  65. }
  66.